<?php

namespace App\Admin\Controllers;

use App\Extensions\ContentSingle;
use App\Extensions\LayerForm;
use App\Rules\MoneyRule;
use App\Transverse;
use App\TransverseBill;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Layout\Content;

class TransverseBillController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '合同到账金额';
    protected $service;

    public function edit($id, Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description['edit'] ?? trans('admin.edit'))
            ->body($this->form()->edit($id));
    }

    public function change($id, ContentSingle $content)
    {
        $form = $this->changeForm();
        if (!request()->isMethod('GET')) {
            return $form->update($id);
        }
        return $content->body($form->edit($id));
    }

    protected function changeForm(): Form
    {
        $form = new LayerForm(new TransverseBill());
        $form->setActionCurrent();
        $form->date('pay_date', '到账时间');
        $form->text('amount', '到账金额')->prepend('$')->rules([new  MoneyRule()]);
        //$form->textarea('remark', '备注');
        Admin::style('.box-footer{min-height:150px}');
        $form->saved(function (Form $form) {
            $transverse = $form->model()->transverse;
            if ($transverse instanceof Transverse) {
                $transverse->in_amount = $transverse->bills()->sum('amount');
                $transverse->save();
                $transverse->writeLog(Admin::user(), '【到账】变更', $form->amount);
            }
        });
        return $form;
    }
}
